<template>
  <div class="search-box">
    <i class="iconfont icon-search"></i>
    <input ref="query" class="box" v-model="query" :placeholder="placeholder" />
    <i @click="clear" v-show="query" class="iconfont icon-dismiss"></i>
  </div>
</template>

<script>
import { debounce } from '../../assets/js/util'

export default {
  name: 'SearchBox',
  props: {
    placeholder: {
      type: String,
      default: '搜索歌曲, 歌手'
    }
  },
  data() {
    return {
      query: ''
    }
  },
  methods: {
    clear() {
      this.query = ''
    },
    setQuery(query) { // 这个函数向外界暴露一个接口来设置input的值, 外界调用这个组件$refs.xxx.setQuery(...)
      this.query = query
    },
    blur() {
      this.$refs.query.blur()
    }
  },
  created() {
    this.$watch('query', debounce((newQuery) => {
      // 派发一个事件, 告诉外面我有变化
      this.$emit('query', newQuery)
    }, 200))
  }
}
</script>

<style lang="scss" scoped>
@import "../../assets/css/variable.scss";

.search-box{
  display: flex;
  align-items: center;
  box-sizing: border-box;
  width: 100%;
  padding: 0 6px;
  height: 40px;
  background: $color-highlight-background;
  border-radius: 6px;
  .icon-search{
    font-size: 24px;
    color: $color-background;
  }
  .box{
    flex: 1;
    margin: 0 5px;
    line-height: 18px;
    background: $color-highlight-background;
    color: $color-text;
    font-size: $font-size-medium;
    outline: none;
    border: none;
    &::placeholder{
      color: $color-text-d;
    }
  }
  .icon-dismiss{
    font-size: 16px;
    color: $color-background;
  }
}
</style>